#!/bin/bash

#for files not in /etc
WORK_PATH="/opt/middleware/AtlasEdge"
SCRIPT_PATH="/opt/middleware/AtlasEdge/software/edge_site/edge_manager/src/script"
backup_base_dir=$WORK_PATH/config/backup
mod_file_list=`cat $SCRIPT_PATH/mod_file_list.txt`
dir_list=`cat $SCRIPT_PATH/mod_file_list.txt | xargs dirname | sort | uniq`

. ${SCRIPT_PATH}/log_util.sh

if [ ! -d $backup_base_dir ];then
    sudo mkdir -p $backup_base_dir
    logger_Debug "create backup dir for etc resume!"
fi

#create dir for ibma edge when first run
#for dir_name in $dir_list
#do
#    if [ ! -d $dir_name ];then
#        mkdir -p $dir_name
#        logger_Info "create dir $dir_name for etc resume!"
#    fi
#done

upgrade_mod_file()
{
    target_file=$1
    backup_file=${backup_base_dir}/$(basename ${target_file})
    mod_check_file="/run/atlasedge_mod_check"

    if [ -f ${mod_check_file}.md5 ]; then
        sudo rm -f ${mod_check_file}.md5
    fi

    if [ -f ${backup_file}.md5 ]; then
        sudo rm -f ${backup_file}.md5
    fi

    #refresh verification for target file!
    sudo sha256sum $target_file | sudo tee ${mod_check_file}.checksum
    sudo dd if=${mod_check_file}.checksum of=${backup_file}.checksum conv=fsync status=none
    #upgrade backup file!
    sudo dd if=$target_file of=${backup_file} conv=fsync status=none
    logger_Debug "upgrade verify and backup for $(basename ${target_file})"
}

# exit func
function exit_trap()
{
    trap - INT TERM EXIT QUIT ABRT
    pkill -P $$
}

main()
{
    trap exit_trap INT TERM EXIT QUIT ABRT

    while read event;
    do
        #flush modify to flash
        sync
        target_file=`echo $event | awk '{print $1 $3}'`
        #target in mod_file_list
        if [[ $mod_file_list =~ "$target_file" ]];then
            upgrade_mod_file $target_file
            #leave a message in log file
            logger_Debug ":found an event $event !"
            #dir modify should be write to flash
            sync
        fi
    done < <(exec inotifywait -mq -e moved_to,delete,close_write -r ${dir_list} --exclude $backup_base_dir )
}

main "$@"
RESULT=$?
exit $RESULT